package com.momo.points.token;

import com.momo.points.exception.IdempotentException;
import com.momo.points.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Service
public class TokenService {

    @Autowired
    RedisUtil RedisUtil;

    /**
     * 生产token
     * @return
     */
    public String generateToken(){
        String uuid = UUID.randomUUID().toString();
        RedisUtil.setEx(uuid,uuid,10000L);
        return uuid;
    }

    /**
     * 检查token
     * @return
     */
    public boolean checkToken(HttpServletRequest request) throws IdempotentException {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            token = request.getParameter("token");
            if(StringUtils.isEmpty(token)){
                throw new IdempotentException("重复操作");
            }
        } else {
            boolean token1 = RedisUtil.exits("token");
            if(!token1){
                throw new IdempotentException("token不存在");
            }
            boolean delete = RedisUtil.delete(token);
            if(!delete){
                throw new IdempotentException("重复操作");
            }
        }
        return true;
    }
}
